<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="${${pageContext.request.contextPath}/js/json2.js"></script>
    <script type="text/javascript">
        function method01(){
            //获取网页中需要传达的数据\
            var usernamevalue =document.getElementById('username').value;
            var usernamevalue =document.getElementById('userpassword').value;
            //步骤1：把数据封装到js对象里
            var jsObject=new Object();
            jsObject.name=usernamevalue;
            jsObject.password=userpasswordvalue;
            //步骤2：把js对象转换成json格式字符串
            var jsonString=JSON.stringify(jsObject);
            console.log('传送的json格式字符串为：'+jsonString+'')
            var xhr=new XMLHttpRequest();
            xhr.open('POST','${pageContext.request.contextPath }/jsonhandler/json01.do');
            ///告诉服务器端  数据的组织方式是json
            xhr.setRequestHeader('Content-Type','application/json');
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        //返回的是json格式字符串
                        var backContet=xhr.responseText;
                        console.log('后台返回的内容为：'+backContet+'。');
                        //把json格式字符串转换成json对象
                        var jsonObjectBack=eval('('+backContet+')');


                        var usernamespan=document.getElementById('usernameback');
                        var userpasswordspan=document.getElementById('userpasswordback');
                        usernamespan.innerHTML=jsonObjectBack.name;
                        userpasswordspan.innerHTML=jsonObjectBack.password;

                    }
                }
            }
            xhr.send(jsonString);
        }
    </script>
</head>
<body>
用户名：<input type="text" id="username" name="name"><br>
密码：<input type="password" id="userpassword" name="password"><br>
<input type="button" value="提交" onclick="method01()">
<input type="button" value="重置">
<hr>
返回的数据：
<br>
用户名：<span id="usernameback"></span><br>
密码：<span id="userpasswordback"></span>
</body>
</html>